var map;
function onLoad() {
    map = new T.Map("mapDiv", {
            projection: "EPSG:4326",
    });
    map.centerAndZoom(new T.LngLat(120.5629, 27.526106), 12);
    map.setMapType(window.TMAP_SATELLITE_MAP);
    var scaleCtrl = new T.Control.Scale("T_ANCHOR_BOTTOM_LEFT");
    map.addControl(scaleCtrl); //添加比例尺控件
    //去除logo
    document.getElementsByClassName(
        "tdt-control-copyright tdt-control"
    )[0].style.display = "none";
    this.map=map;
}

Vue.config.delimiters = ['{[', ']}']
new Vue({
    delimiters: ['{[', ']}'],
    el: "#app",
    data() {
            return {
                selectingImg: 0,//正在选择的图片
                selectedIndex: -1,//已经选择
                switchvalue: false,//截图开关
                fileList: undefined,

                map: undefined,
                zoom: 12,
                imgsrc: [],
                imgsrc2: [],
                yuantu: '',
                position: {
                    x: 0,
                    y: 0,
                    lng: 0,
                    lat: 0,
                },
                is_cut: true,
                // 显示loading
                loading: false,
                PredictStep:0,
                PerdictProcess:0,

                imgbs64src: '',
                dialogVisible: false,
                jtdialogVisible: false,
                xsd: 0,
                upload_file_url: "http://192.168.43.41:5000/upJsonFile",
                preurl: '',
                dialogVisibleHelp: false,

                step1:true,
                step2:false,
                step3:false,
                step4:false,

                algorithms:[
                    {
                        value: '选项1',
                        label: 'Mask_RCNN'
                    },{
                        value: '选项2',
                        label: 'Transformer',
                        disabled: true
                    },
                ],
                algorithm: 'Mask_RCNN'

            };
        },
    methods: {
            init(){
                this.step1=true;
                this.step2=false;
                this.step3=false;
                this.step4=false;
            },
            selectTwice() {
                this.dialogVisible = true;
                this.step4=false;
            },
            selectImgToXsd() {
                console.log('this.selectingImg', this.selectingImg)
                this.selectedIndex = this.selectingImg;
                console.log('selectedIndex====', this.selectedIndex);
                this.dialogVisible = false;

            },
            getxsd() {
                var request = new XMLHttpRequest();
                var url = "http://192.168.43.41:5000/Compare";
                request.open("POST", url);
                request.setRequestHeader("content-type", "application/json"); //先open再设置请求头
                var obj = {
                    index: this.selectedIndex + 1,
                    lnglat: [this.position.lng, this.position.lat],
                };
                console.log(obj);
                var that = this;
                request.onreadystatechange = function () {
                    if (request.readyState == 4) {
                        console.log("request.status===", request.status);
                        if (request.status == 200) {
                            // console.log(this);
                            that.objt1 = request.responseText;
                            that.objt1 = JSON.parse(that.objt1);
                            that.xsd = that.objt1.Same;

                            // console.log(typeof(that.objt1));
                            console.log("上传成功2", that.xsd);
                            that.step4=true;
                        } else {
                            console.log(
                                "相似度上传失败,检查上传地址是否正确",
                                request.responseText
                            );
                        }
                    }
                };

                obj = JSON.stringify(obj);
                request.send(obj);
            },
            //上传文件
            submitUpload() {
                //开始上传
                console.log('上传完毕');
                this.$refs.dataFormFile.submit();
                this.step2=true;
            },
            puterr(response, file, fileList) {
                console.log('response, file, fileList', response, file, fileList);
            },
            putsucess(res) {
                //获取回传的JSON后，赋值
                //创建面对象
                var tmp = res.coordinates[0]
                var points = []
                for (i = 0; i < tmp.length; i++) {
                    points.push(new T.LngLat(tmp[i][0], tmp[i][1]))
                }
                var polygon = new T.Polygon(points, {
                    color: "red", weight: 3, opacity: 0.5, fillColor: "#FFFF", fillOpacity: 0.5
                });
                //向地图上添加面
                map.clearOverLays();
                //同时将中心移动
                console.log("移动")
                map.setZoom(20);
                map.panTo(points[0])
                map.addOverLay(polygon);
                console.log(res);
            },
            handleRemove(file, fileList) {
                console.log(file, fileList);
            },
            handlePreview(file) {
                console.log(file);
            },
            getLngLat(lnglat) {
                this.position.lng = lnglat.lng.toFixed(6);
                this.position.lat = lnglat.lat.toFixed(6);
                //map.panTo(lnglat);
                // 选择是否清除全部覆盖物，添加标记
                var marker = new T.Marker(lnglat);
                map.addOverLay(marker);
                console.log('获得金纬度===', this.position.lng)
            },
            rectClick(event) {
                if (!this.switchvalue) return;
                console.log('获取鼠标点击的位置和经纬度mapevent', event);
                //获取鼠标点击的位置和经纬度
                var config = {
                    callback: this.getLngLat,
                };
                pickup = new T.CoordinatePickup(map, config);
                pickup.addEvent();
                //获取相对于当前所指向对象的位置坐标
                // this.position.x = event.offsetX;
                this.position.y = event.offsetY;
                console.log("this.position===", this.position);
                point = new T.LngLat(0, 0);
                if (this.is_cut) {
                    console.log("start cut");
                    var that = this;
                    setTimeout(function () {
                        that.screenCut();
                    }, 1000);
                }
            },
            screenCut() {
                map.clearOverLays();
                const targetDom = document.querySelector("#mapDiv"); // 获取要截图的元素
                //html2canvas 截图
                html2canvas(targetDom, {
                    useCORS: true,
                    timeout: 500,
                }).then((canvas) => {
                    this.printClip(canvas, 512, 512);
                    let dataURL = canvas.toDataURL("image/png", 1);
                    console.log(dataURL)
                    // 没截好的
                    //  this.downloadImage(dataURL)
                });
            },
            downloadImage(url) {
                // 如果是在网页中可以直接创建一个 a 标签直接下载
                let a = document.createElement("a");
                a.href = url;
                a.download = "天地图截图2";
                a.click();
            },
            printClip(canvas, capture_width, capture_height) {
                var clipCanvas = document.createElement("canvas");
                clipCanvas.width = capture_width;
                clipCanvas.height = capture_height;
                // 截取
                capture_x = this.position.x - capture_width; //这里需要调整去除白边
                capture_y = this.position.y - capture_height;
                if (capture_x < 0) {
                    capture_x = 0;
                }
                if (capture_y < 0) {
                    capture_y = 0;
                }
                clipCanvas
                    .getContext("2d")
                    .drawImage(
                        canvas,
                        capture_x,
                        capture_y,
                        capture_width,
                        capture_height,
                        0,
                        0,
                        capture_width,
                        capture_height
                    );
                //保存
                var clipImgBase64 = clipCanvas.toDataURL("image/png", 1);

                // 弹出出截图
                this.preurl = clipImgBase64;
                this.imgbs64src = clipImgBase64;
                this.jtdialogVisible = true;
            },
            cloimg(res) {
                console.log('弹窗的返回数据===', res);
                this.switchvalue=false;
                this.loading = true;
                var $Blob = this.getBlobBydataURI(this.imgbs64src, "image/jpeg");
                var formData = new FormData();
                formData.append("file", $Blob, "avatar.jpg");
                // console.log('clipImgBase64',clipImgBase64)
                // 组建XMLHttpRequest 上传文件
                var request = new XMLHttpRequest();
                // 上传连接地址
                //request.open("POST",'http://127.0.0.1:5000/upLoadFile');
                request.open("POST", "http://192.168.43.41:5000/perdictImg");
                //request.open("POST", "http://10.0.0.190:5000/perdictImg");

                // return new Promise((resolve, reject) => {
                let that = this;
                request.onreadystatechange = function () {
                    if (request.readyState == 4) {
                        console.log("request.status===", request.status);
                        if (request.status == 200) {
                            console.log("上传成功", request.responseText);
                            console.log(typeof request.responseText);
                            // imgsrc = request.responseText;
                            that.imgsrc = JSON.parse(request.responseText).perdictImgList;
                            console.log("imgsrc===", "data:image/gif;base64," + that.imgsrc);
                            // console.log('imgsrc[0]',imgsrc[0]);
                            console.log(typeof that.imgsrc);
                            // 跳转
                            that.loading = false;
                            that.dialogVisible = true;
                            that.yuantu = that.imgsrc.shift();
                            that.imgsrc2 = that.imgsrc;
                            //location.href="http://127.0.0.1:5000/upLoadFile"
                            that.step3=true;

                        } else {
                            console.log(
                                "上传失败,检查上传地址是否正确",
                                request.responseText
                            );
                            that.$message.error('运行计算出错！');
                            that.loading = false;
                        }
                    }
                };
                // })
                request.send(formData);
            },
            getBlobBydataURI(dataURI, type) {
                var binary = atob(dataURI.split(",")[1]);
                var array = [];
                for (var i = 0; i < binary.length; i++) {
                    array.push(binary.charCodeAt(i));
                }
                return new Blob([new Uint8Array(array)], {type: type});
            },
        },

})
